'use strict';
const Service = require('egg').Service;
const { NotFound } = require('@utils/http-exception');

class OrdersService extends Service {
  async hasOrder(ctx, params) {
    const result = await ctx.model.Orders.findOne({
      where: params,
    });

    return result;
  }

  async add(params) {
    const { ctx } = this;
    const result = await ctx.model.Orders.create(params);
    return result;
  }

  async delete({ houseId }) {
    const { ctx } = this;
    const ret = await this.hasOrder(ctx, {
      userId: ctx.userId,
      houseId,
    });
    if (ret) {
      const result = await ctx.model.Orders.destroy({
        where: { id: ret.id },
      });
      return result;
    }
    throw new NotFound('没有找到可操作的资源');
  }

  async lists(params) {
    const { ctx, app } = this;
    const result = await ctx.model.Orders.findAll({
      where: {
        isPayed: params.type,
        userId: params.userId,
      },
      limit: Number(params.pageSize),
      offset: (params.pageNum - 1) * params.pageSize,
      include: [
        {
          model: app.model.Houses,
          as: 'houses',
          include: [
            {
              model: app.model.Imgs,
              attributes: [ 'url' ],
              limit: 1,
            },
          ],
        },
      ],
    });

    return result;
  }

  async pay(params) {
    const { ctx } = this;
    const ret = await this.hasOrder(ctx, {
      userId: ctx.userId,
      id: params.id,
    });
    if (ret) {
      const result = await ctx.model.Orders.update(
        {
          isPayed: 1,
          orderNumber: params.orderNumber,
        },
        {
          where: {
            id: params.id,
          },
        }
      );
      return result;
    }
    throw new NotFound('没有找到可操作的资源');
  }
}

module.exports = OrdersService;
